package com.movisol.messenger.views;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.movisol.c2dm.events.PushNotificationReceivedEvent;
import com.movisol.c2dm.ilisteners.IPushNotificationReceived;
import com.movisol.messenger.R;
import com.movisol.messenger.controllers.MessengerController;
import com.movisol.messenger.views.controls.ContactRow;
import com.movisol.messengerprofileservice.data.Friend;
import com.movisol.messengerprofileservice.events.DataLoadedEvent;
import com.movisol.messengerprofileservice.helpers.MessengerProfileHelper;
import com.movisol.messengerprofileservice.interfaces.errorcodes.FriendStatus;
import com.movisol.messengerprofileservice.listeners.IFriendsDataLoadedListener;

/**
 * Waiting List page that shows the contacts waiting to be approved 
 * @author Antonio Santiago
 */
public class WaitingListPage extends Activity implements IFriendsDataLoadedListener, OnClickListener,
		IPushNotificationReceived {

	private final MessengerController mc = MessengerController.getInstance();
	private Context context;
	private LinearLayout ll;
	private Button imBtnFriendList;
	private Button imBtnProfile;
	private Button imBtnConversations;
	private AlertDialog ad = null;
	private Friend selectedFriend = null;
	private String sui = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.mainpage);
		getWindow().setFormat(PixelFormat.RGBA_8888);
		getWindow().addFlags(LayoutParams.FLAG_DITHER);
		mc.setCurrentPage(MessengerController.WAITING_PAGE);
		this.context = mc.getContext();
		
		mc.pc.addFriendsDataLoadedListener(this);
		mc.pc.addFriendsDataUpdatedListener(this);
		mc.c2dmc.addPushNotificationsListener(this);
		initializeGUI();
		
		
		String type = getIntent().getStringExtra("type");

		if (type != null && type.equals("c-invRec")) {
			sui = getIntent().getStringExtra("sui");
			mc.loadFriendList();
		}
 else {
			refreshWaitingList();
		}
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		
		// String type = getIntent().getStringExtra("type");
		// if(type != null && type.equals("c-invRec"))
		// {
		// sui = getIntent().getStringExtra("sui");
		// sn = getIntent().getStringExtra("sn");
		// mc.loadFriendList();
		// }

	}

	private void initializeGUI() {
		
		ll = (LinearLayout) findViewById(R.id.layoutContactsMp);
	
		imBtnFriendList = (Button) findViewById(R.id.imBtnProfile);
		imBtnFriendList.setOnClickListener(this);
		
		
		imBtnConversations = (Button) findViewById(R.id.imBtnConversations);
		imBtnConversations.setVisibility(View.GONE);
		
		imBtnProfile = (Button) findViewById(R.id.imBtnProfile);
		imBtnProfile.setVisibility(View.GONE);
		
	}
	
	public void refreshWaitingList()
	{

		ll.removeAllViews();
		
		//Add first the friends that are waiting for my approval
		List<Friend> waiting4ApprovalList = MessengerProfileHelper.filterFriends(mc.pc.getFriends().getFriendList(),FriendStatus.WAITING_FOR_APPROVAL);

		for(Friend friend : waiting4ApprovalList)
		{
			ContactRow newContact = new ContactRow(context, friend);
			newContact.getImageContactRow().setBackgroundResource(R.drawable.img_unknow_waiting);
//			newContact.setOnClickListener(this);
			newContact.setClickable(false);
			if(friend.getFriendStatusId() == FriendStatus.WAITING_FOR_APPROVAL)
				newContact.getContactButton().setBackgroundResource(R.drawable.ic_approve_contact_btn);
			else
				newContact.getContactButton().setBackgroundResource(R.drawable.ic_resend_invitation_btn);
			
			newContact.getContactButton().setOnClickListener(this);
			ll.addView(newContact);
		}
		
		//At last add friends that have to approve me
		List<Friend> waiting4FriendApprovalList = MessengerProfileHelper.filterFriends(mc.pc.getFriends().getFriendList(), FriendStatus.WAITING_FOR_FRIEND_APPROVAL);
		
		for(Friend friend : waiting4FriendApprovalList)
		{
			ContactRow newContact = new ContactRow(context, friend);
			newContact.getImageContactRow().setBackgroundResource(R.drawable.img_unknow_waiting);
//			newContact.setOnClickListener(this);
			newContact.setClickable(false);
			if(friend.getFriendStatusId() == FriendStatus.WAITING_FOR_APPROVAL)
				newContact.getContactButton().setBackgroundResource(R.drawable.ic_approve_contact_btn);
			else
				newContact.getContactButton().setBackgroundResource(R.drawable.ic_resend_invitation_btn);
			
			newContact.getContactButton().setOnClickListener(this);
			ll.addView(newContact);
		}
	}

	
	private void showApproveContact() {
		final TextView textView = new TextView(context);
		textView.setText(selectedFriend.getUserProfile().getCalculatedNickName() + " ("
				+ selectedFriend.getUserProfile().getEmail() + ")");
		textView.setGravity(Gravity.CENTER);
		textView.setTextSize(16);
		textView.setPadding(0, 5, 0, 5);
		
		ad = new AlertDialog.Builder(this)
	    .setTitle("Dou you want to accept the invitation from ")
	    .setView(textView)
	    .setPositiveButton("Accept", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				
				List<String> emailList = new ArrayList<String>();
						emailList.add(selectedFriend.getUserProfile().getEmail());
				mc.approveContact(selectedFriend);
				ad.dismiss();
			}
		})
		.setNegativeButton("Don't Accept", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				ad.dismiss();
			}
		})
	    .show();
	}
	
	
	private void searchContact() {

		for (int i = 0; i < ll.getChildCount(); i++)
			if (((ContactRow) ll.getChildAt(i)).getFriend().getUserProfile().getUserId().equals(sui)) {
				selectedFriend = ((ContactRow) ll.getChildAt(i)).getFriend();
				break;
			}

		
	}
	
	private void showResendInvitation() {
		
		final TextView email = new TextView(context);
		email.setText(selectedFriend.getUserProfile().getEmail());
		email.setGravity(Gravity.CENTER);
		email.setTextSize(16);
		email.setPadding(0, 5, 0, 5);
		
		ad = new AlertDialog.Builder(this)
	    .setTitle("Dou you really want to resend an invitation to:")
	    .setView(email)
	    .setPositiveButton("Resend", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {

				List<String> emailList = new ArrayList<String>();
				emailList.add(email.getText().toString());
				mc.resendInvitation(emailList);
				ad.dismiss();
			}
		})
		.setNegativeButton("No", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				ad.dismiss();
			}
		})
	    .show();
	}


	@Override
	public void friendsDataLoaded(DataLoadedEvent evt) {
		refreshWaitingList();
		if (sui != null) {
			searchContact();
			showApproveContact();
		}
		
	}


	@Override
	protected void onStop() {
		super.onStop();
		mc.pc.removeFriendsDataUpdatedListener(this);
		mc.pc.removeFriendsDataLoadedListener(this);
		mc.c2dmc.removePushNotificationsListener(this);
	}


	@Override
	public void onClick(View v) {
		
		switch(v.getId())
		{
			case R.id.imBtnProfile:
				Intent mainPageIntent = new Intent(this, ProfilePage.class);
				startActivityForResult(mainPageIntent,2);
			break;
			
			
			//Approves the pending invitation
			case R.id.BottomBarImBtn1:
				showApproveContact();
			break;

			
			//Resends the invitation
			case R.id.BottomBarImBtn2:
				showResendInvitation();
			break;

			
			case R.id.btCancelEmail:
				ad.dismiss();
			break;

		}
	

		if(v instanceof Button)
		{
			ContactRow cr = (ContactRow)v.getParent().getParent().getParent().getParent();
			selectedFriend = cr.getFriend();
			if(selectedFriend.getFriendStatusId() == FriendStatus.WAITING_FOR_APPROVAL)
				showApproveContact();
			else
				showResendInvitation();
		}
		
	}

	@Override
	public void pushNotificationReceived(PushNotificationReceivedEvent evt) {
		sui = evt.getPayload();
		mc.loadFriendList();
		// refreshWaitingList();
		// searchContact();
		// showApproveContact();

	}
	
	
}
